package org.example.objevent.event;

import lombok.extern.slf4j.Slf4j;
import org.example.objevent.executor.EventExecutor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class EventBus {

    @Autowired
    private EventBroker broker;

    @Autowired
    private EventExecutor executor;

    public void publish(Event event){

        EventActor actor = broker.getActor(event);

        if(ThreadModel.USE_CURRENT.equals(event.getThreadModel())){
            fireActorAction(actor, event);
            return;

        }

        if(ThreadModel.USE_NEW_THREAD.equals(event.getThreadModel())){
            executor.getExecutor().submit(new AsyncActor(actor, event));
            return;

        }

    }

    private void fireActorAction(EventActor actor, Event event){

        if(actor instanceof FallbackActor){
            actor.act(event);
            return;

        }

        actor.act(event.getData());

    }

    private class AsyncActor implements Runnable{

        private Event event;
        private EventActor eventActor;

        public AsyncActor(EventActor actor, Event event){
            this.event = event;
            this.eventActor = actor;

        }

        @Override
        public void run() {
            fireActorAction(eventActor, event);

        }

    }

}
